import Vue from "vue";
import axios from "axios";
import router from "@/router";
import store from "@/store";

const instance = axios.create({
    // baseURL: 'http://localhost:2000/api/',
    baseURL: 'http://114.116.97.39:2000/api/',
    // baseURL: '/api',  // 配代理
    timeout: 5000
})


// 请求拦截器
instance.interceptors.request.use(config => {
    const token = store.state.token || localStorage.getItem('token');
    if(token) {
        config.headers.token = token
        // config.headers.Authorization = token
    }
    return config
}, error => {
    router.push('/error')
    return Promise.reject(error)
})

// 响应拦截器
instance.interceptors.response.use(response => {
    // 处理 token 已过期 重新登录
    const {data} = response
    if(data.hasOwnProperty('state') && data.hasOwnProperty('msg')){
        if(!data.state){
            Vue.prototype.notifyError(data.msg)
            localStorage.removeItem('token')
            router.push('/login')
            return false;
        }
    }
    return response
}, error => {
    return Promise.reject(error)
})


export default instance